from PyQt5.QtWidgets import QMainWindow
from loguru import logger

from .ui.index import Ui_MainWindow
from .utils.log import log
from .utils.mqtt import Mqtt
from .utils.yamlLoader import YamlLoader
from .widget.DialogToInfo import DialogToInfo


class indexPage(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # 配置文件
        self.config = YamlLoader().get_config()
        # 配置log
        self.log = log
        # 配置mqtt
        self.mqtt = Mqtt(broker=self.config['mqtt']['broker'],
                         port=self.config['mqtt']['port'],
                         client_id=self.config['mqtt']['client_id'],
                         username=self.config['mqtt']['username'],
                         password=self.config['mqtt']['password'],
                         userdata={'config': self.config, 'log': self.log})
        # 启动线程
        self.mqtt.loop_start()

        # 定义按钮点击事件
        self.ui.ledOffBtn.clicked.connect(self.on_led_off_clicked)
        self.ui.ledOnBtn.clicked.connect(self.on_led_on_clicked)

        # 配置 loguru，将日志重定向到 QPlainTextEdit
        self.converter = None
        self.setup_loguru()

    # 按钮点击事件
    def on_led_off_clicked(self):
        """
        触发关灯事件
        """
        try:
            # 订阅灯确认消息
            self.mqtt.subscribe(self.config['topic']['lednews'])
            # 发布灯消息
            self.mqtt.publish(self.config['topic']['led'], self.config['payload']['led']['offPL'])
        except Exception as e:
            self.log.error(f"on_led_off_clicked 出现错误: {e}")
            # 出错弹窗
            DialogToInfo().Error()

    def on_led_on_clicked(self):
        """
        触发开灯事件
        """
        try:
            # 订阅灯确认消息
            self.mqtt.subscribe(self.config['topic']['lednews'])
            # 发布灯消息
            self.mqtt.publish(self.config['topic']['led'], self.config['payload']['led']['onPL'])
        except Exception as e:
            self.log.error(f"on_led_on_clicked 出现错误: {e}")
            # 出错弹窗
            DialogToInfo().Error()

    def setup_loguru(self):
        """
        配置 loguru，将日志重定向到 QPlainTextEdit
        """

        def log_to_plaintextedit(message):
            """
            自定义 sink 函数，将日志内容传递给 QPlainTextEdit
            """
            self.ui.logPTE.append(str.strip(message))

        # 添加自定义 sink 函数
        logger.add(log_to_plaintextedit)

    def closeEvent(self, event):
        """
        关闭窗口时移除自定义 sink 函数
        """
        logger.remove()  # 移除所有 sink 函数
        super().closeEvent(event)
